/**
 * Created with hong.rong
 * Description:类目管理
 * Date:2020/06/24
 */

import React from 'react'
import { Table } from 'antd'
import Search from './components/Search'
import useCategory from './useCategory'
import { LEVEL_ENUM } from '@/constant/category'
import Modify from './components/Modify/index'

export default function Category() {
  const {
    loading,
    searchValue,
    total,
    dataSource,
    handleFetchList,
  } = useCategory()

  const renderColumn = () => {
    return [
      {
        title: '类目ID',
        dataIndex: 'cateId',
      },
      {
        title: '类目名称',
        dataIndex: 'title',
      },
      {
        title: '类目层级',
        dataIndex: 'cateLevel',
        render: v => {
          if (v) return LEVEL_ENUM[`${v}`]
          return ''
        },
      },
      {
        title: '排序',
        dataIndex: 'orderSeq',
      },
      {
        title: '操作',
        dataIndex: 'action',
        width: 60,
        render: (_, r) => (
          <Modify refreshList={() => handleFetchList(searchValue)}>
            {show => (
              <div
                className="link-button"
                onClick={() =>
                  show(Modify.TYPE.EDIT.VALUE, {
                    cateId: r.cateId,
                    title: r.title,
                    cateLevel: r.cateLevel,
                    leaf: r.leaf,
                    oneId: r.oneId,
                    twoId: r.twoId,
                    orderSeq: r.orderSeq,
                    feature: r.feature,
                  })
                }
              >
                编辑
              </div>
            )}
          </Modify>
        ),
      },
    ]
  }

  /**
   * 搜索
   * @param search
   * @returns {Promise<void>}
   */
  const handleSearch = async (search = {}) => {
    await handleFetchList({ ...searchValue, ...search })
  }
  /**
   * 翻页
   * @param pagination
   * @returns {Promise<void>}
   */
  const handlePageChange = async pagination => {
    await handleFetchList({
      ...searchValue,
      page: pagination.current,
      pageSize: pagination.pageSize,
    })
  }

  return (
    <div>
      <Search
        onSearch={handleSearch}
        refreshList={() => handleFetchList(searchValue)}
      />
      <Table
        loading={loading}
        pagination={{
          current: searchValue.page,
          pageSize: searchValue.pageSize,
          total: total,
        }}
        dataSource={dataSource}
        columns={renderColumn()}
        rowKey={(v, i) => i}
        onChange={handlePageChange}
      />
    </div>
  )
}
